<template>
  <div class="app-container">
    <div class="filter-container">

      <el-cascader
          v-if="level == 1"
          class="filter-item"
          v-model="selectParent" :options="distributorsList"
          :props="distributorsProps"
          placeholder="所属经销商"
          @change="getList"
          style="width: 15%;margin-left:15px;" clearable filterable></el-cascader>

      <el-input
          class="filter-item"
          placeholder="输入关键字进行过滤"
          v-model="listQuery.keyword"
          style="width: 15%;margin-left:10px"
      >
      </el-input>

      <el-radio-group v-model="listQuery.is_autoload" style="margin-left: 5px" class="filter-item" @change="getList">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button :label="1">充满自停</el-radio-button>
        <el-radio-button :label="0">充满不停</el-radio-button>
      </el-radio-group>

      <el-radio-group v-model="listQuery.type" style="margin-left: 5px" class="filter-item" @change="getList">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button :label="1">常规套餐</el-radio-button>
        <el-radio-button :label="3">电量套餐</el-radio-button>
      </el-radio-group>

      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList"
                 style="margin-left: 10px"
      >
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate"
      >
        添加套餐
      </el-button>
      <!--      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"-->
      <!--                 @click="handleDownload"-->
      <!--      >-->
      <!--        导出-->
      <!--      </el-button>-->
      <!--      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">-->
      <!--        审核-->
      <!--      </el-checkbox>-->
    </div>
    <el-table v-loading="listLoading" :data="list" fit highlight-current-row style="width: 100%">
      <el-table-column type="expand" align="center" label="详情">
        <template slot-scope="scope">
          <el-card v-if="scope.row.type != 3">
          <el-row :gutter="32">
            <el-divider>功率分档设置</el-divider>
            <el-col :xs="24" :sm="24" :lg="6" v-for="item in scope.row.power_children">
              <el-card>
                <el-form ref="detailForm" :model="item" label-position="left" label-width="120px"
                         style="width: 90%; margin-left:5%; "
                >
                  <el-form-item label="分钟数/每元">
                    <el-input v-model="item.minutes" type="number"/>
                  </el-form-item>
                  <el-form-item label="最小功率范围/w">
                    <el-input v-model="item.min_power" type="number"/>
                  </el-form-item>
                  <el-form-item label="最大功率范围/w">
                    <el-input v-model="item.max_power" type="number"/>
                  </el-form-item>
                </el-form>
                <center>
                  <!--                  <el-button @click="delDetail(item.id)">-->
                  <!--                    删除-->
                  <!--                  </el-button>-->
                  <el-button type="primary" @click="editDetail(item)" v-if="scope.row.distributor_id">
                    保存
                  </el-button>
                </center>
              </el-card>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-divider>充电选项</el-divider>
            <el-col :xs="24" :sm="24" :lg="6" v-for="item in scope.row.time_children">
              <el-card>
                <el-form :model="item" label-position="left" label-width="120px"
                         style="width: 80%; margin-left:10%; "
                >
                  <el-form-item label="金额/元">
                    <el-input v-model="item.fee" type="number"/>
                  </el-form-item>
                  <el-form-item label="分钟数">
                    <el-input v-model="item.minutes" type="number"/>
                  </el-form-item>
                </el-form>
                <center>
                  <!--                  <el-button @click="delDetail(item.id)">-->
                  <!--                    删除-->
                  <!--                  </el-button>-->
                  <el-button type="primary" @click="editDetail(item)">
                    保存
                  </el-button>
                </center>
              </el-card>
            </el-col>
          </el-row>
          </el-card>
          <el-card v-else>
            <el-row :gutter="32">
              <el-divider>电量选项</el-divider>
              <el-col :xs="24" :sm="24" :lg="6" v-for="item in scope.row.elec_children">
                <el-card>
                  <el-form :model="item" label-position="left" label-width="120px"
                           style="width: 80%; margin-left:10%; "
                  >
                    <el-form-item label="金额/元">
                      <el-input v-model="item.fee" type="number"/>
                    </el-form-item>
                  </el-form>
                  <center>
                    <!--                  <el-button @click="delDetail(item.id)">-->
                    <!--                    删除-->
                    <!--                  </el-button>-->
                    <el-button type="primary" @click="editDetail(item)">
                      保存
                    </el-button>
                  </center>
                </el-card>
              </el-col>
            </el-row>

            <el-row :gutter="32">
              <el-divider>服务费分档选项</el-divider>
              <el-col :xs="24" :sm="24" :lg="6" v-for="item in scope.row.service_children">
                <el-card>
                  <el-form :model="item" label-position="left" label-width="120px"
                           style="width: 80%; margin-left:10%; "
                  >
                    <el-form-item label="元/每小时">
                      <el-input v-model="item.fee" type="number"/>
                    </el-form-item>
                    <el-form-item label="功率范围（小）">
                      <el-input v-model="item.min_power" type="number"/>
                    </el-form-item>
                    <el-form-item label="功率范围（大）">
                      <el-input v-model="item.max_power" type="number"/>
                    </el-form-item>
                  </el-form>
                  <center>
                    <!--                  <el-button @click="delDetail(item.id)">-->
                    <!--                    删除-->
                    <!--                  </el-button>-->
                    <el-button type="primary" @click="editDetail(item)">
                      保存
                    </el-button>
                  </center>
                </el-card>
              </el-col>
            </el-row>

          </el-card>
        </template>

      </el-table-column>
      <el-table-column align="center" label="ID" min-width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="120" align="center" label="名称">
        <template slot-scope="scope">
          <el-link type="success">{{ scope.row.name }}</el-link>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>
      <el-table-column min-width="80" align="center" label="所属经销商">
        <template slot-scope="scope">
          <el-tag type="success">{{ scope.row.distributor_name }}</el-tag>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>

      <el-table-column min-width="80" align="center" label="充满自停">
        <template slot-scope="scope">
          <el-link type="success" v-if="scope.row.is_autoload == 1">开启</el-link>
          <el-link type="primary" v-else>关闭</el-link>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" min-width="120">
        <template slot-scope="scope">
          <el-button type="success" v-if="scope.row.distributor_id" size="mini" @click="detailCreate(scope.row)">
            添加子规则
          </el-button>
          <el-button type="primary" v-if="scope.row.distributor_id" size="mini" @click="handleUpdate(scope.row)">
            编辑
          </el-button>
          <el-button type="primary" v-else size="mini" @click="handleUpdate(scope.row)">
            查看
          </el-button>
          <el-button type="danger" v-if="scope.row.distributor_id" size="mini" @click="del(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"
    />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="35%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px"
               style="width: 90%; margin-left:5%;"
      >

        <el-form-item label="所属经销商" v-if="level == 1">
          <el-cascader v-model="editDistributor" ref="cascaderDistributors" :options="distributorsList"
                       :props="distributorsProps"
                       placeholder="不选择则为自身套餐"
                       style="width: 80%" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="temp.name" style="width: 80%"/>
        </el-form-item>
        <el-form-item label="充满自停金额">
          <el-input v-model="temp.fee" style="width: 80%" type="number"/>
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="temp.sort" style="width: 80%" type="number"/>
        </el-form-item>
        <el-form-item label="最低消费金额">
          <el-input v-model="temp.pre_fee" style="width: 80%"/>
        </el-form-item>
        <el-form-item label="充满自停">
          <el-radio-group v-model="temp.is_autoload" prop="type">
            <el-radio-button :label="1">是</el-radio-button>
            <el-radio-button :label="0">否</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="套餐类型">
          <el-radio-group v-model="temp.type" prop="type">
            <el-radio-button :label="1">常规套餐</el-radio-button>
            <el-radio-button :label="3">电量套餐</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="服务费收取方式" v-if="temp.type == 3">
          <el-radio-group v-model="temp.service_type" prop="type">
            <el-radio-button :label="1">每度</el-radio-button>
            <el-radio-button :label="2">每小时</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="服务费/单价"  v-if="temp.type == 3">
          <el-input v-model="temp.service_fee" style="width: 80%" type="number"/>
        </el-form-item>

        <el-form-item label="电价/每度"  v-if="temp.type == 3">
          <el-input v-model="temp.elec_price" style="width: 80%" type="number"/>
        </el-form-item>

        <el-form-item label="最高使用电量"  v-if="temp.type == 3">
          <el-input v-model="temp.elec" style="width: 80%" type="number"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <center>
          <el-button @click="resetForm">
            取消
          </el-button>
          <el-button type="primary" v-if="temp.distributor_id" @click="dialogStatus==='create'?createData():createData()">
            提交
          </el-button>
        </center>
      </div>
    </el-dialog>


    <el-dialog :title="detailTitle" :visible.sync="detailFormVisible" width="35%">
      <el-form ref="detailForm" :rules="rules1" :model="detailTemp" label-position="left" label-width="120px"
               style="width: 80%; margin-left:10%; "
      >
        <el-card v-if="detailTemp.type < 3">
          <el-form-item label="选项">
            <el-radio-group v-model="detailTemp.type" @change="handleChangeMode">
              <el-radio :label="1">功率分档设置</el-radio>
              <el-radio :label="2">充电选项</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="金额/元" v-if="detailTemp.type == 2">
            <el-input v-model="detailTemp.fee" style="width: 70%" type="number"/>
          </el-form-item>
          <el-form-item :label="detailTemp.type==2 ?'分钟数':'分钟数/每元'">
            <el-input v-model="detailTemp.minutes" style="width:70%" type="number"/>
          </el-form-item>
          <el-form-item label="最小功率范围/w" v-if="detailTemp.type == 1">
            <el-input v-model="detailTemp.min_power" style="width:70%" type="number"/>
          </el-form-item>
          <el-form-item label="最大功率范围/w" v-if="detailTemp.type == 1">
            <el-input v-model="detailTemp.max_power" style="width:70%" type="number"/>
          </el-form-item>
        </el-card>
        <el-card v-else>
          <el-form-item label="选项">
          <el-radio-group v-model="detailTemp.type" @change="handleChangeMode">
            <el-radio :label="3">金额选项</el-radio>
            <el-radio :label="4">服务费分档</el-radio>
          </el-radio-group>
          </el-form-item>
          <el-form-item label="金额/元">
            <el-input v-model="detailTemp.fee" style="width: 70%" type="number"/>
          </el-form-item>
          <el-form-item label="最小功率范围/w" v-if="detailTemp.type == 4">
            <el-input v-model="detailTemp.min_power" style="width:70%" type="number"/>
          </el-form-item>
          <el-form-item label="最大功率范围/w" v-if="detailTemp.type == 4">
            <el-input v-model="detailTemp.max_power" style="width:70%" type="number"/>
          </el-form-item>
<!--          <el-form-item label="电价/每度">-->
<!--            <el-input v-model="detailTemp.elec_price" style="width:70%" type="number"/>-->
<!--          </el-form-item>-->
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <center>
          <el-button @click="resetDetail">
            取消
          </el-button>
          <el-button type="primary" @click="createDetail()">
            提交
          </el-button>
        </center>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getList, create, del} from '@/api/charge_option'
import {createDetail, delDetail} from '@/api/charge_detail'
import {all} from '@/api/distributors'
// import { getMenus } from '@/api/menu'
import Pagination from '@/components/Pagination'
import store from '@/store'
import router from '@/router' // Secondary package based on el-pagination
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'
import {formatMoney} from '@/api/util'

export default {
  name: 'ChargeList',
  components: {Pagination, ImageCropper, PanThumb},
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    ttlipsis(value) {
      if (!value) return ''
      if (value.length > 18) {
        return value.slice(0, 18) + '...'
      }
      return value
    },
    moenyFormat(value) {
      if (!value) return ''
      return formatMoney(value)
    }

  },
  data() {
    return {
      editDistributor: '',
      detailFormVisible: false,
      detailTitle: '',
      selectParent: '',
      distributorsProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true
      },
      imagecropperShow: false,
      imagecropperKey: 0,
      menus: [],
      roles: [],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        keyword: '',
        distributor_id: '',
        is_autoload: '',
        type: ''
      },
      temp: {
        id: undefined,
        is_autoload: 1,
        distributor_id: '',
        name: '',
        fee: '',
        sort: 0,
        type: '',
        service_type: '',
        service_fee: '' ,
        elec:3,
        elec_price:'',
        pre_fee:''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      distributorsList: [],
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      nowType: 1,
      level:'',
      rules: {
        name: [{required: true, message: '套餐名称不能为空', trigger: 'blur'}],
        type: [{required: true, message: '类型为必选项', trigger: 'blur'}],
        // password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      rules1: {},
      detailType: '',
      detailTemp: {
        id: undefined,
        charge_option_id: 0,
        type: '',
        fee: '',
        minutes: 0,
        min_power: 0,
        max_power: 0
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.level = this.$store.getters.introduction
    this.getList()
    this.getSelector()
  },
  methods: {
    handleChangeMode(e) {
      if (e == 1) {
        this.temp.distributor_id = ''
      }
    },
    cropSuccess(resData) {
      this.imagecropperShow = false
      this.imagecropperKey = this.imagecropperKey + 1
      this.temp.avatar = resData.url
    },
    close() {
      this.imagecropperShow = false
    },
    getList() {
      this.listLoading = true
      if (Array.isArray(this.selectParent)) {
        this.listQuery.distributor_id = this.selectParent[this.selectParent.length - 1];
      } else {
        if (this.selectParent) {
          this.listQuery.distributor_id = this.selectParent
        } else {
          this.listQuery.distributor_id = ''
        }
      }
      getList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    resetForm() {
      this.dialogFormVisible = false
    },
    resetDetail() {
      this.detailFormVisible = false
    },
    handleCreate() {

      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    delDetail(id) {
      this.$confirm('确认要删除该条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delDetail(id).then(response => {
          // this.list.unshift(this.temp)
          if (response.code == 200) {
            this.$notify.success({
              title: '成功',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            this.resetTemp()
            this.getList()
          } else {
            this.$notify.error({
              title: '失败',
              message: response.msg,
              duration: 2000
            })
          }
        })
      }).catch(() => {

      })
    },
    editDetail(item) {
      createDetail(item).then(response => {
        this.detailFormVisible = false
        if (response.code == 200) {
          this.$notify.success({
            title: '成功',
            message: response.msg,
            type: 'success',
            duration: 2000
          })
          this.resetDetailTemp()
          this.getList()
        } else {
          this.$notify.error({
            title: '失败',
            message: response.msg,
            duration: 2000
          })
        }
      })
    },
    createDetail() {
      createDetail(this.detailTemp).then(response => {
        this.detailFormVisible = false
        if (response.code == 200) {
          this.$notify.success({
            title: '成功',
            message: response.msg,
            type: 'success',
            duration: 2000
          })
          this.resetDetailTemp()
          this.getList()
        } else {
          this.$notify.error({
            title: '失败',
            message: response.msg,
            duration: 2000
          })
        }
      })
    },
    createData() {
      if (Array.isArray(this.editDistributor)) {
        this.temp.distributor_id = this.editDistributor[this.editDistributor.length - 1];
      } else {
        if (!this.editDistributor) {
          this.temp.distributor_id = 0
        } else {
          this.temp.distributor_id = this.editDistributor
        }
      }
      if (this.temp.sort == '') {
        this.temp.sort = 0
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          create(this.temp).then(response => {
            // this.list.unshift(this.temp)
            this.dialogFormVisible = false
            if (response.code == 200) {
              this.$notify.success({
                title: '成功',
                message: response.msg,
                type: 'success',
                duration: 2000
              })
              this.resetTemp()
              this.getList()
            } else {
              this.$notify.error({
                title: '失败',
                message: response.msg,
                duration: 2000
              })
            }
          })
        }
      })
    },
    getSelector() {
      all('all').then(response => {
        this.distributorsList = response.data
      })
    },
    handleUpdate(row) {

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.temp = Object.assign({}, row) // copy obj
      this.editDistributor = row.distributor_id
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    detailCreate(row) {
      this.detailTitle = '添加' + row.name + '子规则'
      this.detailFormVisible = true
      this.resetDetailTemp()
      this.detailTemp.type = row.type
      this.detailTemp.charge_option_id = row.id
    },
    del(id) {
      this.$confirm('确认要删除该条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(id).then(response => {
          // this.list.unshift(this.temp)
          if (response.code == 200) {
            this.$notify.success({
              title: '成功',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            this.resetTemp()
            this.getList()
          } else {
            this.$notify.error({
              title: '失败',
              message: response.msg,
              duration: 2000
            })
          }
        })
      }).catch(() => {

      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        is_autoload: 1,
        distributor_id: '',
        name: '',
        fee: '',
        sort: '',
        type: '',
        service_type: '',
        service_fee: '',
        elec:3,
        elec_price:'',
        pre_fee:''
      }
    },
    resetDetailTemp() {
      this.detailTemp = {
        id: undefined,
        charge_option_id: 0,
        type: 1,
        fee: '',
        minutes: 0,
        min_power: 0,
        max_power: 0
      }
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}

.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
<style scoped>
.avatar {
  width: 200px;
  height: 200px;
  border-radius: 50%;
}
</style>

<style>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
